﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text.Json;
using WorldmeServer.Models.Base;
using WorldmeServer.Models.用户相关;

namespace WorldmeServer.Middlewares
{
    public class JwtHandler
    {
        private readonly RequestDelegate _next;

        public JwtHandler(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            bool needAuth = false;
            var endpoint = context.GetEndpoint();
            var allowany = endpoint?.Metadata.FirstOrDefault(a => a.GetType() == typeof(JwtNoAuthorizeAttribute));
            if (allowany == null)
            {
                needAuth = true;
            }

            var token = context.Request.Headers["Authorization"].ToString();

            if (needAuth && !string.IsNullOrEmpty(token))
            {
                token = token.Replace("Bearer ", "");
                var handler = new JwtSecurityTokenHandler();
                var jwtToken = handler.ReadJwtToken(token);

                // 获取 "User" Claim
                var userClaim = jwtToken.Claims.FirstOrDefault(c => c.Type == "User");
                if (userClaim != null)
                {
                    // 反序列化用户信息
                    var user = JsonSerializer.Deserialize<User>(userClaim.Value);
                    if (user != null)
                    {
                        // 将用户信息存储在 HttpContext.Items 中
                        context.Items["User"] = user;
                    }
                }
            }
            else if (needAuth)
            {
                throw new Exception("未授权的请求");
            }
            await _next(context);
        }
    }

    public static class JwtHandlerExtensions
    {
        public static IApplicationBuilder UseCustomJwtHandler(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<JwtHandler>();
        }
    }
}
